package org.keyintegrity.webbeans;

import org.apache.tapestry.form.IPropertySelectionModel;
import org.keyintegrity.webbeans.utils.BeanUtils;

public class EnumSelectionModel implements IPropertySelectionModel {

    public final Class enumType;
    private final Object[] enumConstants;
    
    public EnumSelectionModel(Class enumType) {
        if (enumType == null) {
            throw new NullPointerException("enumType is null");
        }
        if (! enumType.isEnum()) {
            throw new IllegalArgumentException(enumType.getName() + " is not enum type");
        }
        this.enumType = enumType;
        enumConstants = enumType.getEnumConstants();
    }

    public String getLabel(int index) {
        if (index == 0) {
            return "<null>";
        }
        return BeanUtils.getValueAsString(enumConstants[index - 1]);
    }

    public Object getOption(int index) {
        if (index == 0) {
            return null;
        }
        return enumConstants[index - 1];
    }

    public int getOptionCount() {
        return enumConstants.length + 1;
    }

    public String getValue(int index) {
        return enumType.getName() + '_' + index;
    }

    public Object translateValue(String value) {
        int index = Integer.valueOf(value.substring(value.indexOf('_') + 1)).intValue();
        if (index == 0) {
            return null;
        }
        return enumConstants[index - 1];
    }

}
